﻿@model Tasker.WebUI.Models.Profile.ProfileEditModel

@{
    ViewBag.Title = "Редактирование профиля";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="@Url.Content("~/Content/tasker-jquery-fileupload-ui.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/tasker-jquery-jcrop.css")" rel="stylesheet" type="text/css" />

<script src="@Url.Content("~/Scripts/Custom/tasker-jquery-fileupload-ui.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Custom/tasker-jquery-fileupload.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Custom/tasker-jquery-Jcrop-min.js")" type="text/javascript"></script>

@section Sidebar
{
    <script type="text/javascript">
        $(function () {

            $("#tasker-dialog-modal").dialog({
                autoOpen: false,
                resizable: false,
                width: 700,
                modal: true
            });


        });
    </script>
    
    <img src="@Url.Content("~/" + Model.PicturePath)" width="165px" />
    <a href="javascript:;" onclick="$('#tasker-dialog-modal').dialog('open');" style="display: block;" >Загрузить фотографию</a>
    <div id="tasker-dialog-modal" title="Upload picture">
        <div style="padding: 0.5em 0;display:block;" class="awe-morebtn">
            @using (Html.BeginForm("UploadPicture", "Profile", FormMethod.Post, new {id="file_upload", enctype="multipart/form-data"}))
            {
                <input type="file" name="fileUpload" />
                <button>
                    Загрузить
                </button>
                <div>
                    Перетащите мышкой изображение в эту зону
                </div>
            }
            <table id="files">
            </table>
        </div>
        <div class="cropbox" style="width: 350px; float: left;">
            <img id="cropbox" src="@Url.Content(@"~/" + Tasker.Common.Paths.DefaultUserPhoto)" style="max-width: 350px;" alt="" />
        </div>

        <div class='thumbhead ui-widget-header' style="margin-left: 400px;">
            preview
        </div>
        <div class="fl thumb" style="width: 200px; overflow: hidden;margin-left: 400px;height: 200px;">
                <img src="@Url.Content(@"~/" + Tasker.Common.Paths.DefaultUserPhotoThumb)" id="preview" alt="" />
         </div>
        
        <div class="fl" style="width: 210px;">
            
            <div class="fl" style="margin: 0.6em 0">
                
                @using (Html.BeginForm("CropPicture", "Profile", FormMethod.Post, new { @class = "cropform" }))
                {   
                    <input type="hidden" id="iw" name="iw" value="0"/>
                    <input type="hidden" id="ih" name="ih" value="0" />
                    <input type="hidden" id="x" name="x" value="0"/>
                    <input type="hidden" id="y" name="y" value="0"/>
                    <input type="hidden" id="w" name="w" value="0"/>
                    <input type="hidden" id="h" name="h" value="0"/>
                    <input type="hidden" id="filename" name="filename" value=""/>
                    <button type="submit" style="width: 200px;" class="awe-btn">save image</button>
                   
                }
                
            </div>
            
        </div>
        <script type="text/javascript">
            function updatePic(o) {
                $('#dasPicture').attr('src', '@Url.Content("~/" + Tasker.Common.Paths.UserPhotosDir)' + o.name + '?' + Math.random());
                picChanged = true;
            }
            function check() {
                if ($('#filename').val().length == 0) { alert('select an image first'); return false; }
                return true;
            }
            var picChanged = false;
            $(function () {
                //updateMeal function is from Meal/Index.cshtml
                //awesomePopup is the id of the div generated by the Html.Awe().Popup
                $('#awesomePopup').bind('dialogclose', function () {
                    if (picChanged) {
                        picChanged = false;
                        updateMeal($('#id').val());
                    }
                });
                $('#file_upload').fileUploadUI({
                    uploadTable: $('#files'),
                    downloadTable: $('#files'),
                    buildUploadRow: function (files, index) {
                        return $('<tr><td>' + files[index].name + '<\/td>' +
                            '<td class="file_upload_progress"><div><\/div><\/td>' +
                            '<td class="file_upload_cancel">' +
                            '<button class="ui-state-default ui-corner-all" title="Cancel">' +
                            '<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
                            '<\/button><\/td><\/tr>');
                    },
                    buildDownloadRow: function (file) {
                        $('#cropbox, #preview').attr('src', '@Url.Content("~/" + Tasker.Common.Paths.ContentTempDir)' + file.name);
                        $('#filename').val(file.name);
                        dw = Math.min(350, file.w);
                        dh = Math.round(dw * file.h / file.w);
                        $('#cropbox').width(dw).height(dh);
                        //$('#cropbox').width(file.w).height(file.h);
                        //dw = $('#cropbox').width(); //file.w;
                        //dh = $('#cropbox').height(); //file.h;

                        $('#iw').val(dw);
                        $('#ih').val(dh);
                        docrop();
                        return $('');
                    },
                    addNode: function (parentNode, node, callBack) {
                        parentNode.empty();
                        parentNode.append(node);
                        if (typeof callBack === 'function') {
                            callBack();
                        }
                    }
                });
            });

            var api;
            function docrop() {

                if (api) api.destroy();

                api = $.Jcrop('#cropbox', {
                    setSelect: [0, 0, 200, 200],
                    onChange: showPreview,
                    onSelect: showPreview,
                    aspectRatio: 1.0
                });
            }

            function updateCoords(c) {
                $('#x').val(c.x);
                $('#y').val(c.y);
                $('#w').val(c.w);
                $('#h').val(c.h);
            }

            function showPreview(coords) {
                updateCoords(coords);

                if (parseInt(coords.w) > 0) {
                    var rx = 200 / coords.w;
                    var ry = 200 / coords.h;

                    $('#preview').css({
                        width: Math.round(rx * dw) + 'px',
                        height: Math.round(ry * dh) + 'px',
                        marginLeft: '-' + Math.round(rx * coords.x) + 'px',
                        marginTop: '-' + Math.round(ry * coords.y) + 'px'
                    });
                }
            }
        </script>
    </div>
}

<script type="text/javascript">
    
    var activeEmails,
        activePhones,
        curId = 0;

    function currentId() {
        var res = curId;
        curId++;
        return res;
    }

    function valOrDefault(dict, param, _default) {
        if (dict != null && typeof dict != 'undefined' && param in dict)
            return dict[param];
        return _default;
    }
    


    ///////////////////
    
    function Phone(emObject, id) {
        this.id = id;
        this.phone = valOrDefault(emObject, 'phone', '');
        this.renderToHtml = function() {
            var html = '<div class="phone-row"> \
                           <input type="hidden" name="phones" value="' + this.phone  + '"/> \
                           <span class="phone-sp">' + this.phone + '</span> \
                           <a href="javascript:;" class="btn btn-danger" onclick="activePhones.deletePhone(' + this.id + ');">X</a> \
                        </div>';
            return html;
        };
        this.equal = function(obj) {
            return this.phone == obj.phone;
        };
    }

    function ActivePhones(emObject) {
        self = this;
        this.phones = {};
        @foreach (var tw in Model.Phones)
        {
            <text>
                id = currentId();
                this.phones[id] = new Phone({
                    'phone': '@tw'
                }, id);
            
            </text>
        }
        
        curId = this.phones.length;
        if(typeof curId == 'undefined') curId = 0;
        function isExisted(phone) {
            var res = false;
            for(var i in self.phones) {
                if(phone.equal(self.phones[i])) {
                    res = true;
                    break;
                }
            }
            return res;
        };
        
        this.renderToHtml = function () {
            var html = '';
            for (var i in this.phones) {
                html += '<li id="p-container-' + this.phones[i].id + '">' + this.phones[i].renderToHtml() + '</li>';
            }
            return html;
        };

        this.addPhone = function(obj) {
            var em = new Phone(obj, currentId());
            if(isExisted(em)) {
                alert("This phone is existed!");
            } else {
                this.phones[em.id] = em;
                $('#phone-list').append('<li id="p-container-' + em.id + '">' + em.renderToHtml() + '</li>');    
            }
                
        };

        this.deletePhone = function(id) {
            if(id in this.phones) {
                $('#phone-list li#p-container-' + id).remove();
                delete this.phones[id];
            }
        };

        this.init = function() {
            $('#phone-list').html(activePhones.renderToHtml());
        };
    }

    activePhones = new ActivePhones();
    

    function addPhone() {
        var srcLangObj = '#phone-input';
        activePhones.addPhone({
            'phone': $(srcLangObj).val()
        });
    }

    ///////////////////

    function Email(emObject, id) {
        this.id = id;
        this.email = valOrDefault(emObject, 'email', '');
        this.renderToHtml = function() {
            var url = '@Url.Content("~/Content/images/community/arrow.png")';
            var html = '<div class="email-row"> \
                           <input type="hidden" name="emails" value="' + this.email  + '"/> \
                           <span class="email-sp">' + this.email + '</span> \
                           <a href="javascript:;" class="btn btn-danger" onclick="activeEmails.deleteEmail(' + this.id + ');">X</a> \
                        </div>';
            return html;
        };
        this.equal = function(obj) {
            return this.email == obj.email;
        };
    }

    function ActiveEmails(emObject) {
        self = this;
        this.emails = {};
        @foreach (var tw in Model.Emails)
        {
            <text>
                id = currentId();
                this.emails[id] = new Email({
                    'email': '@tw'
                }, id);
            
            </text>
        }
        
        curId = this.emails.length;
        if(typeof curId == 'undefined') curId = 0;
        function isExisted(email) {
            var res = false;
            for(var i in self.emails) {
                if(email.equal(self.emails[i])) {
                    res = true;
                    break;
                }
            }
            return res;
        };
        
        this.renderToHtml = function () {
            var html = '';
            for (var i in this.emails) {
                html += '<li id="em-container-' + this.emails[i].id + '">' + this.emails[i].renderToHtml() + '</li>';
            }
            return html;
        };

        this.addEmail = function(obj) {
            var em = new Email(obj, currentId());
            if(isExisted(em)) {
                alert("This email is existed!");
            } else {
                this.emails[em.id] = em;
                $('#email-list').append('<li id="em-container-' + em.id + '">' + em.renderToHtml() + '</li>');    
            }
                
        };

        this.deleteEmail = function(id) {
            if(id in this.emails) {
                $('#email-list li#em-container-' + id).remove();
                delete this.emails[id];
            }
        };

        this.init = function() {
            $('#email-list').html(activeEmails.renderToHtml());
        };
    }

    activeEmails = new ActiveEmails();
    

    function addEmail() {
        var srcLangObj = '#email-input';
        activeEmails.addEmail({
            'email': $(srcLangObj).val()
        });
    }

    $(document).ready(function () {
        activeEmails.init();
        activePhones.init();
    });

</script>

<h2>Редактирование профиля</h2>

@using (Html.BeginForm("Edit", "Profile", FormMethod.Post, new {id="edit-form"}))
{
    <div class="emp-block">
        <div class="ui-helper-clearfix row bigger">
            <div class="c1">
                @Html.LabelFor(m => m.FirstName)
            </div>
            <div class="c2">
                <div class="wdt">
                    @Html.TextBoxFor(m => m.FirstName)
                </div>
            </div>
        </div>
    </div>

    <div class="emp-block">
        <div class="ui-helper-clearfix row bigger">
            <div class="c1">
                @Html.LabelFor(m => m.LastName)
            </div>
            <div class="c2">
                <div class="wdt">
                    @Html.TextBoxFor(m => m.LastName)
                </div>
            </div>
        </div>
    </div>

    <div class="emp-block">
        <div class="ui-helper-clearfix row bigger">
            <div class="c1">
                @Html.LabelFor(m => m.Position)
            </div>
            <div class="c2">
                <div class="wdt">
                    @Html.TextBoxFor(m => m.Position)
                </div>
            </div>
        </div>
    </div>

    <div class="emp-block">
        <div class="ui-helper-clearfix row bigger">
            <div class="c1">
                @Html.LabelFor(m => m.Comment)
            </div>
            <div class="c2">
                <div class="wdt">
                    @Html.TextAreaFor(m => m.Comment)
                </div>
            </div>
        </div>
    </div>
    
    <div class="emp-block">
        <div class="ui-helper-clearfix row bigger">
            <div class="c1">
                Email
            </div>
            
            <div class="wdt" style="margin-left: 103px;">
                <input id="email-input" type="text" />
                <a href="javascript:;" onclick="addEmail();" class="btn" style="vertical-align: top;">
                    +
                </a>
                <ul id="email-list">
                </ul>
            </div>
            
        </div>
    </div>
    
    <div class="emp-block">
         <div class="ui-helper-clearfix row bigger">
            <div class="c1">
                Телефоны
            </div>
            
                <div class="wdt" style="margin-left: 103px;">
                    <input id="phone-input" type="text" />
                    <a href="javascript:;" onclick="addPhone();" class="btn" style="vertical-align: top;">
                        +
                    </a>
                    <ul id="phone-list">
                    </ul>
                </div>
            
        </div>
    </div>
    
    <a href="javascript:;" class="btn btn-primary" onclick="$('#edit-form').submit();">
        Сохранить
    </a>
}

